import React, { useEffect, useRef, useState } from 'react'
import { View, Image, StyleSheet, Animated } from 'react-native'
import { TouchableOpacity } from 'react-native-gesture-handler'
import icon_heart from '../../../assets/icon_heart.png'
import icon_heart_empty from '../../../assets/icon_heart_empty.png'

type Props = {
  value: boolean;
  onValueChanged?: (value: boolean) => void;
  size?: number;
}

export default function Heart(props: Props) {
  const { value, onValueChanged } = props;
  const [show, setShow] = useState(false)


  // 创建动画
  const scale = useRef<Animated.Value>(new Animated.Value(0)).current;
  const alpha = useRef<Animated.Value>(new Animated.Value(0)).current;


  const changeShow = () => {
    const newShow = !show
    setShow(newShow)
    onValueChanged?.(newShow);

    if (newShow) {
      alpha.setValue(1);
      const scaleAnim = Animated.timing(scale, {
        toValue: 1.8,
        duration: 300,
        useNativeDriver: false,
      });

      const alphaAnim = Animated.timing(alpha, {
        toValue: 0,
        duration: 400,
        useNativeDriver: false,
        delay: 100, // 延迟100ms
      });

      Animated.parallel([scaleAnim, alphaAnim]).start(); // 动画同步执行
    } else {
      scale.setValue(0);
      alpha.setValue(0);
    }


  }

  useEffect(() => {
    setShow(value);  // 初始化点赞
  }, [value]);

  return (
    <TouchableOpacity
      onPress={changeShow}
    >
      <Image
        style={styles.container}
        source={show ? icon_heart : icon_heart_empty}
      />
      <Animated.View style={{
        width: 20,
        height: 20,
        borderRadius: 10,
        borderWidth: 1,
        position: 'absolute',
        borderColor: '#ff2442',
        transform: [
          { scale: scale }
        ],
        opacity: alpha,
      }} />
    </TouchableOpacity>
  )
}

const styles = StyleSheet.create({
  container: {
    width: 20,
    height: 20,
    resizeMode: 'contain',
  }
})
